#!/usr/bin/env bash
# bash <(curl -sLk https://gitee.com/uon/script/raw/master/shell/synology/sn.sh)
# sn=$1
# mac1=$2
# mac2=$3

driva=("$(ls /dev/sd??)")
drivb=("$(ls /dev/synoboot*)")
driv=(${driva[@]} ${drivb[@]})
echo "${driv[@]}"

bootdv=""
[ ! -d /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a ] && mkdir -p /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a

for i in "${driv[@]}"; do
    echo "检测 ${i}"
    if (mount -t vfat "$i" /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/); then
        echo "挂载成功"
        if [ -f /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg ]; then

            bootdv="$i"
            echo 检测到引导分区
            echo "引导分区 ${bootdv}"
            echo
            cat /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg | grep -Po '(?<=set\s)(sn|mac1|mac2)=.*' && echo
            break
        fi
        umount -v /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a
    fi
done

function change() {
    sn=$1
    mac1=$2
    mac2=$3
    [ "$1" ] && sed -ri "s/(set sn=).*/\1${sn}/g" /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg
    [ "$2" ] && sed -ri "s/(set mac1=).*/\1${mac1}/g" /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg
    [ "$3" ] && sed -ri "s/(set mac2=).*/\1${mac2}/g" /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg

    cat /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a/grub/grub.cfg | grep -Po '(?<=set\s)(sn|mac1|mac2)=.*' && echo
}

if [ "$@" ]; then
    change "$@"

fi

umount -v /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a && [ -d /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a ] && rm -rf /tmp/9cd168ec-f431-4d79-9930-ccc26888de3a
